package com.gee.thread.translator;

import com.gee.thread.VariableDemo;
import com.gee.thread.flow.executor.ExecuteContext;
import com.gee.thread.flow.executor.NextWork;
import com.gee.thread.flow.translator.V2PTranslator;
import com.gee.thread.flow.work.AbstractWork;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * desc:
 *    D单元接口参数转换器,
 *    将Variable中的参数 doubleVar 加起来
 *    将所有的必须前置项的结果加起来
 *    如果存在非必须前置项, 将第一个运行成功地非必须前置项的结果 加起来
 * @author gee wrote on  2021-01-17 11:22:07
 */
public class DV2PTranslator1 implements V2PTranslator<VariableDemo, Double> {


    @Override
    public Double translate(AbstractWork<VariableDemo, Double, ?> currentWork,
                            ExecuteContext<VariableDemo> executeContext) {
        Double doubleVar = executeContext.getVariable().getDoubleVar();

        List<Object> preNecessaryResult = new ArrayList<>();
        currentWork.getWorkExecuteProperties().getPreWorks().forEach((preId, preWork) ->{
            Map<String, ? extends NextWork<VariableDemo, ?>> nextWorks = preWork.getWorkExecuteProperties().getNextWorks();
            if (nextWorks.get(currentWork.getId()).getNecessaryForNext()){
                preNecessaryResult.add(executeContext.getWorkResult(preId).getResult());
            }
        });

        for (Object r : preNecessaryResult) {
            doubleVar += Double.parseDouble(r.toString());
        }

        AtomicReference<String> preFUSWorkId = currentWork.getWorkExecuteProperties().getPreFUSWorkId();
        if (preFUSWorkId.get() != null){
            System.out.println("DV2PTranslator1  preFUSWorkId: " + preFUSWorkId.get());
            Object preFUSWorkResult = executeContext.getWorkResult(preFUSWorkId.get()).getResult();
            doubleVar += Double.parseDouble(preFUSWorkResult.toString());
        }
        return doubleVar;
    }
}
